﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using TSMonitor.Core;

namespace TSMonitor
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private WindowState _lastWindowState;
		private IObservable<IList<TaskInfo>> _tasksObservable;

		public ObservableCollection<TaskInfo> LatestTaskList { get; set; }

		public MainWindow()
		{
			InitializeComponent();
		}

		protected override void OnInitialized(EventArgs e)
		{
			base.OnInitialized(e);
			_lastWindowState = WindowState;

			LatestTaskList = new ObservableCollection<TaskInfo>();
			var viewSource = new CollectionViewSource();
			viewSource.Source = LatestTaskList;

			viewSource.GroupDescriptions.Add(new PropertyGroupDescription("ServerInfo.TargetServer"));
			taskGrid.DataContext = viewSource;
			taskGrid.ItemsSource = viewSource.View;

			var servers = new ServerInfoRepository().GetRegisteredServers();

			_tasksObservable = new TaskObservable(servers, TimeSpan.FromSeconds(5));

			_tasksObservable.Subscribe(OnTaskListUpdated);
		}

		private void OnTaskListUpdated(IList<TaskInfo> taskList)
		{
			notifyIcon.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
											 new Action(
												delegate()
												{
													LatestTaskList.Clear();
													foreach (var taskInfo in taskList)
													{
														LatestTaskList.Add(taskInfo);
													}
													//notifyIcon.ShowBalloonTip(5);
												}
												));
		}

		private void OnNotifyIconDoubleClick(object sender, MouseButtonEventArgs e)
		{
			if (e.ChangedButton == MouseButton.Left)
			{
				Show();
				WindowState = _lastWindowState;
			}
		}

		protected override void OnStateChanged(EventArgs e)
		{
			if (WindowState == WindowState.Minimized)
			{
				Hide();
			}
			else
			{
				_lastWindowState = WindowState;
			}

			base.OnStateChanged(e);
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			e.Cancel = true;
			Hide();
			base.OnClosing(e);
		}


		private void OnOpenClick(object sender, RoutedEventArgs e)
		{
			Show();
		}

		private void OnExitClick(object sender, RoutedEventArgs e)
		{
			notifyIcon.Visibility = Visibility.Hidden;
			Application.Current.Shutdown();
		}

		private void RunTask_Click(object sender, RoutedEventArgs e)
		{
			var selectedTask = (TaskInfo)taskGrid.SelectedItem;

			new TaskRunner().RunTask(selectedTask);
		}
	}
}
